package com.ssh.cp.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.ssh.cp.iservice.IPropertyService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class PropertyAction {
	private String libraryname;
	private int libraryid;
	private ActionContext ctx;
	private InputStream inputStream; 
	private JSONObject result;//用作Json结果
	
	@Autowired
	private IPropertyService propertyService;
	
	public String createLibrary() throws UnsupportedEncodingException {
		ctx=ActionContext.getContext();
		
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		propertyService.addLibrary(libraryname, userid);
		System.out.println("===========libraryname:"+libraryname);
		
		
		inputStream = new ByteArrayInputStream(("成功创建库:"+libraryname).getBytes("UTF-8"));
		
		return "success";
	}

	
	public String listUserLibrary() {
		ctx=ActionContext.getContext();
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		List<?> list=null;
		list=propertyService.listUserLibrary(userid);
		result=new JSONObject();
		JSONArray array =JSONArray.fromObject(list);		
		
		result.put("data",array);
		
		return "success";
	}
	
	public String delLibrary() throws Exception {
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		System.out.println("===========libraryid:"+libraryid);
		propertyService.delLibrary(libraryid, userid);
		
		inputStream = new ByteArrayInputStream(("成功删除库").getBytes("UTF-8"));
		
		return "success";
	}
	
	public String renameLibrary() throws Exception {
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		System.out.println("===========libraryid:"+libraryid);
		propertyService.renameLibrary(userid, libraryid,libraryname);;
		
		inputStream = new ByteArrayInputStream(("成功修改库").getBytes("UTF-8"));
		
		return "success";
	}
	
	
	
	public String getLibraryname() {
		return libraryname;
	}

	public void setLibraryname(String libraryname) {
		this.libraryname = libraryname;
	}


	public ActionContext getCtx() {
		return ctx;
	}


	public void setCtx(ActionContext ctx) {
		this.ctx = ctx;
	}


	public JSONObject getResult() {
		return result;
	}


	public void setResult(JSONObject result) {
		this.result = result;
	}


	public InputStream getInputStream() {
		return inputStream;
	}


	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}


	public int getLibraryid() {
		return libraryid;
	}


	public void setLibraryid(int libraryid) {
		this.libraryid = libraryid;
	}



}
